package com.example.lx5_22.park

import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.lx5_22.adapter.ParkAdapter
import com.example.lx5_22.databinding.ActivityPackingBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = "/app/PackingActivity")
class PackingActivity : BaseActivity<ActivityPackingBinding,ParkViewModel>() {

    val parkAdapter by lazy { ParkAdapter() }
    override fun initView() {
        binding.rvPark.apply {
            adapter = parkAdapter
            layoutManager = LinearLayoutManager(this@PackingActivity)
        }
        lifecycleScope.launch {
            viewModel.getPark().collect{
                parkAdapter.submitData(it)
            }
        }

        val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val left = ItemTouchHelper.LEFT
                return makeMovementFlags(0, left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                val id = parkAdapter.snapshot().items[position].id
                viewModel.getDeletePark(id!!)
                parkAdapter.notifyItemRemoved(position)
            }

        })
        itemTouchHelper.attachToRecyclerView(binding.rvPark)


    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            viewModel.getPark().collect{
                parkAdapter.submitData(it)
            }
        }

        binding.ivAdd.setOnClickListener {
            ARouter.getInstance().build("/app/AddParkActivity").navigation()
        }
    }

    override fun initData() {
        viewModel.deleteParkData.observe(this){
            ToastUtils.showLong("删除成功")
        }
    }
}